<!-- 「我的团队」页面 -->
<template>
  <div class="container">
    <!-- 头部区域 -->
    <div class="header">
      <image
        class="team-avatar"
        :src="teamInviteCompetition?.teamAvatar"
        mode="aspectFill"
      />
      <div class="team-baseinfo">
        <div class="team-name">{{ teamInviteCompetition?.teamName }}</div>
        <AuthBox :hasAuth="teamInviteCompetition?.auth_status === '1'" />
      </div>
      <uni-icons
        type="right"
        size="18"
        color="#BDBDBD"
        class="right-arrow"
        @click="navigateTo('edit-team-profile')"
      ></uni-icons>
    </div>
    <!-- 团队排名区域 -->
    <div class="team-rank" @click="navigateTo('team-invitation-competition')">
      <span>团队排名：</span>
      <span class="red">{{ teamInviteCompetition?.rank }}</span>
      <span class="grey">
        （团队积分：{{ teamInviteCompetition?.score }}）
      </span>
      <uni-icons
        type="right"
        size="18"
        color="#BDBDBD"
        class="right-arrow"
        @click="navigateTo('team-invitation-competition')"
      ></uni-icons>
    </div>
    <!-- 团队成员区域 -->
    <div class="team-member">
      <div class="title">
        团队成员
        <span class="grey">（获奖后，奖励发放团长账号）</span>
      </div>
      <div class="list">
        <div
          v-for="(member, index) in teamInviteCompetition?.teamMemberList"
          :key="member.userId"
          class="item"
        >
          <div class="avatar" :class="index === 0 ? 'captain' : ''">
            <image class="img" :src="member.avatar" mode="aspectFill" />
          </div>
          <div class="nickname">
            {{ member.nickname }}
          </div>
          <div class="score">{{ member.score }}积分</div>
          <image
            class="delete-btn"
            :src="IMG_URL.DUSTBIN"
            @click="onClickDeleteBtn(index)"
          />
        </div>
      </div>
      <div class="tip">建议团长根据团队成员贡献比分奖金哦～</div>
    </div>
    <!-- 任务列表 -->
    <div class="instantly-get-score">
      <div class="title">快速获得积分</div>
      <div class="list">
        <div v-for="task in taskList" :key="task.text" class="task-item">
          <image class="icon" :src="task.icon" />
          <div class="text">
            {{ task.text }}
          </div>
        </div>
      </div>
    </div>
    <!-- 按钮列表 -->
    <div class="btn-list">
      <button v-if="isShowQuitBtn" class="quit-btn" @click="onClickQuitBtn">
        退出团队
      </button>
      <button
        class="invite-btn"
        :open-type="
          (teamInviteCompetition?.teamMemberList?.length || 0) <
          TEAM_PEOPLE_LIMIT
            ? 'share'
            : undefined
        "
        @click="onClickInviteBtn"
      >
        邀请主持好友加入团队
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reqKickOutTeamMember, reqQuitTeam } from "@/api/activity-202310-api";
import AuthBox from "@/components/activity-202410/AuthBox.vue";
import {
  IMG_URL,
  TEAM_PEOPLE_LIMIT,
} from "@/static/constant/activity-202405-constant";
import { useActivity202310 } from "@/stores/activity-202310-store";
import { inviteJoinTeam } from "@/utils/activity-202310-utils";
import { back, navigateTo } from "@/utils/navigate";
import { showToast } from "@/utils/tools";

const activity202310Store = useActivity202310();
const { teamInviteCompetition, personInfo202310, isTeamCaptain } =
  storeToRefs(activity202310Store);
const { setTeamInviteCompetitionData, setPersonInfo202310 } =
  activity202310Store;

const taskList = ref([
  {
    icon: IMG_URL.PEOPLE_CIRCLE_YELLOW,
    text: "组建8人团队奖励2000积分",
  },
  {
    icon: IMG_URL.CALENDAR,
    text: "每日签到奖励50积分",
  },
  {
    icon: IMG_URL.APP,
    text: "每日登录嗨喵App得100积分",
  },
  {
    icon: IMG_URL.SCREENHBGAME,
    text: "多玩红包口袋游戏",
  },
]);

// 团队如果未认证需要在taskList中添加认证任务
if (teamInviteCompetition.value?.auth_status !== "1") {
  taskList.value.splice(2, 0, {
    icon: IMG_URL.CALENDAR,
    text: "联系客服完成真实团队认证得1000积分",
  });
}

// #region 团队信息的获取和展示相关

/** 检查是否有团队信息，没有则获取信息 */
const checkAndGetTeamInfo = async () => {
  if (!personInfo202310.value?.userId) {
    setPersonInfo202310();
  }
  if (!teamInviteCompetition.value) {
    setTeamInviteCompetitionData();
  }
};

onShow(() => {
  checkAndGetTeamInfo();
});

onPullDownRefresh(async () => {
  await Promise.all([setPersonInfo202310(), setTeamInviteCompetitionData()]);

  uni.stopPullDownRefresh();
});

// #endregion

// #region 删除或退出团队相关
const myIndex = computed(() =>
  teamInviteCompetition.value?.teamMemberList.findIndex(
    (item) => item.userId === personInfo202310.value?.userId
  )
);

/** 是否显示退出团队按钮 */
const isShowQuitBtn = computed(() => {
  const myScore = teamInviteCompetition.value?.teamMemberList.find(
    (item) => item.userId === personInfo202310.value?.userId
  )?.score;

  console.log("myScore", myScore);
  console.log("isTeamCaptain", isTeamCaptain.value);
  return !isTeamCaptain.value && myScore === 0;
});

/** 点击退出团队按钮 */
const onClickQuitBtn = async () => {
  try {
    const teamName = teamInviteCompetition.value?.teamName;
    const modelRes = await uni.showModal({
      title: "提示",
      content: `确定退出"${teamName}"吗？`,
    });

    if (!modelRes.confirm) return;

    const quitTeamRes = await reqQuitTeam();
    if (quitTeamRes.data.data.code !== 200) {
      throw new Error(quitTeamRes.data.data.msg || "退出团队失败，请稍后再试");
    }

    showToast("退出团队成功");

    setTimeout(() => {
      back();
      setPersonInfo202310();
      setTeamInviteCompetitionData();
    }, 800);
  } catch (err) {
    showToast(err.msg || "退出团队失败，请稍后再试");
    console.error(err);
  }
};

/** 是否显示删除按钮
 * @param index 当前成员的索引
 * @param score 积分
 */
const isShowDeleteBtn = (index: number, score: number) => {
  if (!isTeamCaptain.value) return false;
  if (score !== 0) return false;

  return true;
};

/** 点击删除按钮功能
 * @param index 当前成员的索引
 */
const onClickDeleteBtn = (index: number | undefined) => {
  if (index === undefined) return;

  let memberName = teamInviteCompetition.value?.teamMemberList[index].nickname;
  let teamName = teamInviteCompetition.value?.teamName;
  uni.showModal({
    title: "删除",
    content: `确定让"${memberName}"退出"${teamName}"吗?`,
    success: async (res) => {
      if (res.confirm) {
        const kickOutTeamMemberRes = await reqKickOutTeamMember(
          teamInviteCompetition.value?.teamMemberList[index].userId || ""
        );
        if (kickOutTeamMemberRes.data.data.code === 200) {
          uni.showToast({
            title: "删除团队成员成功",
            icon: "none",
          });
          setPersonInfo202310();
          setTeamInviteCompetitionData();
        } else {
          uni.showToast({
            title:
              kickOutTeamMemberRes.data.data.msg ||
              "删除团队成员失败，请稍后再试",
            icon: "error",
          });
        }
      }
    },
  });
};
// #endregion

// #region 邀请好友相关

/** 点击邀请好友 */
const onClickInviteBtn = () => {
  if ((teamInviteCompetition.value?.teamMemberList?.length || 0) > 3) {
    uni.showToast({
      title: "团队人数已满",
      icon: "none",
    });
  }
};

/** 邀请好友进团队 */
onShareAppMessage(() => inviteJoinTeam());

// #endregion
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  min-height: 100vh;

  background-color: $page-bg-color;

  padding: 16px 16px calc(30px + env(safe-area-inset-bottom));
  display: grid;
  grid-template:
    "header" min-content
    "." 25px
    "team-rank" min-content
    "." 10px
    "team-member" min-content
    "." 10px
    "instantly-get-score" min-content
    "." 1fr
    "." 40px
    "btn-list" min-content
    / 1fr;

  .header {
    grid-area: header;
    display: flex;
    height: 150rpx;
    background: #ffffff;
    border-radius: 15rpx;
    padding: 0 30rpx 0 19rpx;
    align-items: center;
    .team-avatar {
      width: 104rpx;
      height: 104rpx;
      background: #000000;
      border-radius: 79rpx;
    }
    .team-baseinfo {
      margin-left: 23rpx;
      flex: 1;
      .team-name {
        width: 400rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 42rpx;
        font-weight: 400;
        color: #333333;
      }
    }
  }

  .team-rank {
    grid-area: team-rank;

    width: 100%;
    height: 88rpx;
    background-color: #fff;
    border-radius: 8px;

    padding: 0 30rpx 0 19rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;

    font-size: 16px;
    color: #333;

    .red {
      color: #ff2459;
    }

    .grey {
      color: #a5a5a5;
    }

    .right-arrow {
      margin-left: auto;

      width: 12px;
      height: 12px;
    }
  }

  .team-member {
    grid-area: team-member;

    width: 100%;

    background-color: #fff;
    border-radius: 8px;

    padding: 12px 16px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    row-gap: 16px;
    align-items: center;

    .title {
      align-self: flex-start;

      font-size: 16px;
      color: #333;

      .grey {
        color: #a5a5a5;
      }
    }

    .list {
      width: 100%;

      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .item {
        width: 100%;

        display: grid;
        grid-template:
          "avatar nickname score delete-btn" min-content
          / min-content 1fr max-content 14px;
        column-gap: 10px;
        align-items: center;

        .avatar {
          width: 32px;
          height: 32px;

          .img {
            width: 100%;
            height: 100%;

            border: 1px solid #5769ff;
            border-radius: 50%;
          }

          &.captain {
            position: relative;

            &::after {
              position: absolute;
              top: 0;
              right: -10px;

              width: 20px;
              height: 10px;

              content: "团长";

              background: #ff2459;
              border: 0.5px solid #fff;
              border-radius: 58px;

              display: flex;
              align-items: center;
              justify-content: center;

              font-size: 6px;
              color: #fff;
            }
          }
        }

        .nickname {
          font-size: 14px;
          color: #333;
        }

        .score {
          justify-self: end;

          font-size: 14px;
          color: #ff2459;
        }

        .delete-btn {
          width: 14px;
          height: 14px;
        }
      }
    }

    .tip {
      justify-self: center;

      width: 74.6667vw;

      background-color: #eef0ff;

      padding: 4px 32px;
      display: flex;
      align-items: center;
      justify-content: center;

      font-size: 12px;
      color: #5769ff;
    }
  }

  .instantly-get-score {
    grid-area: instantly-get-score;

    width: 100%;

    background-color: #fff;
    border-radius: 8px;

    padding: 12px 16px;
    box-sizing: border-box;
    row-gap: 16px;

    .title {
      margin-bottom: 16px;

      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .list {
      width: 100%;

      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .task-item {
        width: 100%;

        display: flex;
        column-gap: 8px;
        align-items: center;

        .icon {
          width: 36px;
          height: 36px;
        }

        .text {
          font-size: 18px;
          color: #333;
        }
      }
    }
  }

  .btn-list {
    grid-area: btn-list;

    position: sticky;
    bottom: calc(30px + env(safe-area-inset-bottom));
    left: 0;

    display: flex;
    column-gap: 16px;

    .quit-btn,
    .invite-btn {
      height: 36px;

      border-radius: 41px;

      padding: 8px 0;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;

      font-size: 15px;
      color: #fff;
    }

    .quit-btn {
      background: #c1c1c1;
      flex: 1;
    }

    .invite-btn {
      background: $button-bg;
      flex: 2;
    }
  }
}
</style>
